package com.scau.jansing.dao;

import com.scau.jansing.entities.Student;
import com.scau.jansing.utils.Bean;
import com.scau.jansing.utils.HibernateUtils;
import org.hibernate.Session;

import java.util.List;

/**
 * Created by jansing on 2015/11/19.
 */
@Bean
public class StudentDao {
    public void add(Student student) {
        Session session = HibernateUtils.getSession();
        try {
            session.beginTransaction();
            session.save(student);
            session.getTransaction().commit();
        } finally {
            if (session != null)
                session.close();
        }
    }

    public void update(Student student) {
        Session session = HibernateUtils.getSession();
        try {
            session.beginTransaction();
            session.update(student);
            session.getTransaction().commit();
        } finally {
            if (session != null)
                session.close();
        }
    }

    public void delete(String number) {
        Session session = HibernateUtils.getSession();
        try {
            session.beginTransaction();
            session.createQuery("delete from Student s where s.number=:number")
                    .setString("number", number)
                    .executeUpdate();
            session.getTransaction().commit();
        } finally {
            if (session != null)
                session.close();
        }
    }

    public List<Student> list() {
        Session session = HibernateUtils.getSession();
        try {
            return session.createQuery("from Student").list();
        } finally {
            if (session != null)
                session.close();
        }
    }

    public Student load(String number) {
        Session session = HibernateUtils.getSession();
        try {
            return (Student) session.createQuery("from Student s where s.number=:number")
                    .setString("number", number)
                    .uniqueResult();
        } finally {
            if (session != null)
                session.close();
        }
    }

}
